'''
# Coding:utf-8
# Project: iiop
# Author: rtf
# Time: 2024-06-21 10:54:42
# FileName: read_docx.py
# Software: PyCharm
'''


import json
import copy
from pathlib import Path
from docx import Document
from func.read_word_images import extract_images_with_positions
from func.read_word_table import table_positions, table_to_html


# 定义需要匹配的前缀集合
prefixes = {
    "1总论",  "2现状分析", "3建设方案", "3项目需求分析", "4建设方案", "4设计方案", "5软硬件设计", "6估算书", "7估算书"
}


def read_word_to_json(file_path, fs_type_code, project_type_code):
    # 获取当前脚本所在目录
    current_dir = Path(__file__).resolve().parent
    # 获取项目根目录（假设项目根目录与当前脚本目录同级）
    project_root = current_dir.parent

    file_path = f'{project_root}/{file_path}'

    if fs_type_code == "NON_PURCHASE":
        from func.non_purchase import title_to_key, dict_key
    else:
        if project_type_code == "SOFTWARE_HARDWARE":
            from func.software_hardware import title_to_key, dict_key
        else:
            from func.purchase_category import title_to_key, dict_key
        from func.sd_table import table1_data_process, table2_data_process, table3_data_process

    # 使用 deepcopy 初始化 result 变量，确保每次调用函数时都是新的实例
    result = copy.deepcopy(dict_key)

    # 读取Word文档
    doc = Document(file_path)
    current_key = None
    quotation = list()
    current_factory = {}

    image_positions = extract_images_with_positions(doc)
    image_dict = {str(pos['paragraph_index']): pos['image_filename'] for pos in image_positions}

    tables_position = table_positions(doc)
    tables = table_to_html(doc)
    table_dict = dict()
    # print(tables_position)
    for index, item in enumerate(tables_position):
        if index < len(tables_position) - 3:
          table_dict[str(item)] = tables[0]

    for i, paragraph in enumerate(doc.paragraphs):
        text = paragraph.text.strip().replace(" ", "")
        # 检查文本是否以指定前缀开始
        if any(text.startswith(prefix) for prefix in prefixes):
            continue
        if text in title_to_key:
            current_key = title_to_key[text]
        else:
            if text == "表-1":
                current_key = None
            if current_key:
                if current_key in result["general_remarks"]:
                    result["general_remarks"][current_key] += f'<span style="font-family: 仿宋_GB2312;">&nbsp; &nbsp;{text}</span><br/>'
                    if image_dict.get(str(i + 1)):
                        result["general_remarks"][current_key] += f'<p> <img src="{image_dict.get(str(i + 1))}" alt="" /></p>'
                    if table_dict.get(str(i)):
                        result["general_remarks"][current_key] += table_dict.get(str(i + 1))
                elif current_key in result["situation_analysis"]:
                    result["situation_analysis"][current_key] += f'<span style="font-family: 仿宋_GB2312;">&nbsp; &nbsp;{text}</span><br/>'
                    if image_dict.get(str(i + 1)):
                        result["situation_analysis"][current_key] += f'<p> <img src="{image_dict.get(str(i + 1))}" alt="" /></p>'
                    if table_dict.get(str(i)):
                        result["situation_analysis"][current_key] += table_dict.get(str(i))
                elif current_key in result["demand_analysis"]:
                    result["demand_analysis"][current_key] += f'<span style="font-family: 仿宋_GB2312;">&nbsp; &nbsp;{text}</span><br/>'
                    if image_dict.get(str(i + 1)):
                        result["demand_analysis"][current_key] += f'<p> <img src="{image_dict.get(str(i + 1))}" alt="" /></p>'
                    if table_dict.get(str(i)):
                        result["demand_analysis"][current_key] += table_dict.get(str(i))
                elif current_key in result["construction_plan"]:
                    result["construction_plan"][current_key] += f'<span style="font-family: 仿宋_GB2312;">&nbsp; &nbsp;{text}</span><br/>'
                    if image_dict.get(str(i + 1)):
                        result["construction_plan"][current_key] += f'<p> <img src="{image_dict.get(str(i + 1))}" alt="" /></p>'
                    if table_dict.get(str(i)):
                        result["construction_plan"][current_key] += table_dict.get(str(i))
                elif current_key in result["design"]:
                    result["design"][current_key] += f'<span style="font-family: 仿宋_GB2312;">&nbsp; &nbsp;{text}</span><br/>'
                    if image_dict.get(str(i + 1)):
                        result["design"][current_key] += f'<p> <img src="{image_dict.get(str(i + 1))}" alt="" /></p>'
                    if table_dict.get(str(i)):
                        result["design"][current_key] += table_dict.get(str(i))
                elif current_key in result["material_inventory"]:
                    result["material_inventory"][current_key] += f'<span style="font-family: 仿宋_GB2312;">&nbsp; &nbsp;{text}</span><br/>'
                    if image_dict.get(str(i + 1)):
                        result["material_inventory"][current_key] += f'<p> <img src="{image_dict.get(str(i + 1))}" alt="" /></p>'
                    if table_dict.get(str(i)):
                        result["material_inventory"][current_key] += table_dict.get(str(i))
                elif current_key in result["estimate"]:
                    result["estimate"][current_key] += f'<span style="font-family: 仿宋_GB2312;">&nbsp; &nbsp;{text}</span><br/>'
                    if image_dict.get(str(i + 1)):
                        result["estimate"][current_key] += f'<p> <img src="{image_dict.get(str(i + 1))}" alt="" /></p>'
                    if table_dict.get(str(i)):
                        result["estimate"][current_key] += table_dict.get(str(i))
            else:
                if text.startswith("厂家名称:") or text.startswith("厂家名称："):
                    if current_factory:  # 保存上一个厂家的信息
                        quotation.append(current_factory)
                    current_factory = {
                        "no": len(quotation) + 1,
                        "name": text.replace("厂家名称:", "").strip(),
                        "contact_number": "",
                        "contact_person": "",
                        "quotation_path": ""
                    }
                elif text.startswith("厂家联系人:") or text.startswith("厂家联系人："):
                    current_factory["contact_person"] = text.replace("厂家联系人:", "").strip()
                elif text.startswith("厂家联系方式:") or text.startswith("厂家联系方式："):
                    current_factory["contact_number"] = text.replace("厂家联系方式:", "").strip()
                    current_factory["quotation_path"] = image_dict.get(str(i + 1))
                elif text.startswith("项目申报单位:") or text.startswith("项目申报单位："):
                    result["reporting_unit"] = text
                elif text.startswith("编制单位:") or text.startswith("编制单位："):
                    result["edit_unit"] = text
                else:
                    pass

    if current_factory:  # 保存最后一个厂家的信息
        quotation.append(current_factory)
    result["quotation"] = quotation

    # 遍历文档中的每个表格
    table_num = len(doc.tables)
    for index, table in enumerate(doc.tables):
        table_data = []
        for i, row in enumerate(table.rows):
            if i == 0:
                continue
            row_data = [cell.text.strip() for cell in row.cells]
            table_data.append(row_data)
        if fs_type_code != "NON_PURCHASE":
            if index == table_num - 3:
                result["table1"] = table1_data_process(table_data)
            elif index == table_num - 2:
                result["table2"] = table2_data_process(table_data)
            elif index == table_num - 1:
                result["table3"] = table3_data_process(table_data)
                pass
    return result


# file_path = '/download/20240624/上线前贯通测试（软硬件购置及开发实施模板）.docx'
# json_content = read_word_to_json(file_path, "PURCHASE_CATEGORY", "SOFTWARE_HARDWARE")
# # 将结果打印为JSON格式
# print(json.dumps(json_content, ensure_ascii=False, indent=4))